/*
 * Created on Mar 30, 2006
 */
package com.mgmaps.gps;

import javax.microedition.io.*;
import com.mgmaps.app.APPSettings;
import com.mgmaps.utils.ExtLogger;

/**
 * Receiver for GPS information as NMEA statements over bluetooth (JSR-82).
 *
 * @author CristiS
 * @version 1.0
 */
public class GPSBluetooth extends GPSNMEA {

  // have we printed a connect error message?
  private boolean msgPrinted;
  
  // if the first connection fails, don't try again
  private boolean firstConnect;
  
  // were we ever connected
  private boolean wasConnected;
  
  // did we attempt a connection
  private boolean attempted;
  
  /**
   * Constructor for GPSBluetooth.
   */
  public GPSBluetooth() {
    super();
    
    // don't auto-start
    // start();
  }
  
  /**
   * Activate this receiver.
   */
  public synchronized void activate() {
    firstConnect = true;
    super.activate();
  }
  
  /**
   * Connect to a bluetooth URL.
   * 
   * @return true if the connection was established
   */
  public synchronized boolean connect() {
    if (firstConnect || wasConnected) {
      firstConnect = false;
      try {
        if (APPSettings.gpsDevice.length() == 0 || !APPSettings.gpsDevice.startsWith("btspp://"))
          return false;
        connection = Connector.open(APPSettings.gpsDevice);
        is = ((StreamConnection) connection).openDataInputStream();
        connected = true;
        wasConnected = true;
        ExtLogger.debug("(Re-)connected to GPS");
      }
      catch (Exception ex) {
        if (!msgPrinted) {
          msgPrinted = true;
          ExtLogger.handle(ex, false, "Error connecting to GPS");
        }
        disconnect(false);
      }
      
      attempted = true;
    }

    return connected;
  }
  
  public boolean connectError() {
    return attempted && !connected;
  }
  
  /**
   * Override setQuitting.
   * 
   * @see com.mgmaps.gps.GPSReceiver#notifyExit()
   */
  public synchronized void notifyExit() {
    quitting = true;
    /* if (Props.waitForThreads)
      deactivate();
    else */
      notify();
  }
}
